package com.imooc.course.server.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.imooc.course.server.dao.RoleDao;
import com.imooc.course.server.dto.RoleDto;
import com.imooc.course.server.dto.PageDto;
import com.imooc.course.server.entity.Role;
import com.imooc.course.server.entity.RoleExample;
import com.imooc.course.server.service.RoleService;
import com.imooc.course.server.utils.CopyUtil;
import com.imooc.course.server.utils.UuidUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service("roleService")
public class RoleServiceImpl implements RoleService {

    private static final Logger log = LoggerFactory.getLogger(RoleServiceImpl.class);

    @Resource(name = "roleDao")
    private RoleDao roleDao;

    /**
     * 列表查询
     * @param pageDto
     */
    @Override
    public void getList(PageDto pageDto) {
        PageHelper.startPage(pageDto.getPage(),pageDto.getSize());

        RoleExample roleExample = new RoleExample();
        List<Role> roleList = roleDao.selectByExample(roleExample);

        PageInfo<Role> rolePageInfo = new PageInfo<>(roleList);
        pageDto.setTotal(rolePageInfo.getTotal());

        List<RoleDto> roleDtoList = CopyUtil.copyList(roleList, RoleDto.class);

        pageDto.setList(roleDtoList);
    }

    /**
     * 保存，id有值为更新，id无值为新增
     * @param roleDto
     */
    @Override
    public void save(RoleDto roleDto) {
        Role copy = CopyUtil.copy(roleDto, Role.class);
        String id = roleDto.getId() != null ? roleDto.getId().trim() : roleDto.getId();
        if (StringUtils.isEmpty(id)) {
            this.addRole(copy);
        }else{
            this.updateRole(copy);
        }
    }

    private void updateRole(Role copy) {
        roleDao.updateByPrimaryKeySelective(copy);
    }

    private void addRole(Role copy) {
        copy.setId(UuidUtil.getShortUuid());
        roleDao.insertSelective(copy);
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void delete(String id) {
        roleDao.deleteByPrimaryKey(id);
    }
}
